// 十六进制转rgba
const input = document.querySelector('#input');
const transfer = document.querySelector('#transfer');
const reverseColor = document.querySelector('#reverseColor');
const reverseColor_display = document.querySelector('#reverseColor_display');
const rgba = document.querySelector('#rgba')
const rgba_display = document.querySelector('#rgba_display');
transfer.onclick = () => {
  if (!input.value) return;
  reverseColor.value = this.colorReverse(input.value);
  reverseColor_display.style.backgroundColor = reverseColor.value
  rgba.value = this.hexToRgba(input.value);
  rgba_display.style.backgroundColor = rgba.value
}
// rgba转十六进制
const input_r = document.querySelector('#input_r');
const transfer_r = document.querySelector('#transfer_r');
const reverseColor_r = document.querySelector('#reverseColor_r');
const reverseColor_r_display = document.querySelector('#reverseColor_r_display');
const rgba_r = document.querySelector('#rgba_r')
const rgba_r_display = document.querySelector('#rgba_r_display');
transfer_r.onclick = () => {
  if (!input_r.value) return;
  reverseColor_r.value = this.colorReverse(this.rgbaToHex(input_r.value));
  reverseColor_r_display.style.backgroundColor = reverseColor_r.value
  rgba_r.value = this.rgbaToHex(input_r.value);
  rgba_r_display.style.backgroundColor = rgba_r.value
}
// 获取图片主色调
const upload = document.querySelector('#upload')
const upload_img = document.querySelector('#upload_img');
const upload_r = document.querySelector('#upload_r');
const upload_r_display = document.querySelector('#upload_r_display');
upload.onclick = () => {
  doInput()
}
// <!-- 获取canvas画布上主色调，然后对主色调去反色差的颜色 -->
/**
 * 获取画布上主色调
 * @param {*} ctx 画布对象
 */
this.getImageMainColor = function(canvas) {
  const ctx = canvas.getContext('2d');
  const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
  const rgbaData = data.reduce((accumulator, currentValue, index) => {
      if (index % 4 === 0 && data[index + 3] !== 0) {
          let rgba = `rgba(${data[index]}, ${data[index + 1]}, ${data[index + 2]}, ${(data[index + 3] / 255)})`;
          accumulator[rgba] = (accumulator[rgba] + 1) || 1;
      }
      return accumulator;
  }, {});
  // 对象转数组后 降序排序
  const sortList = [...Object.entries(rgbaData)].sort((a, b) => b[1] - a[1])
  // 获取颜色最多的一个
  return sortList[0][0]
}
/**
 * 16进制色值获取反色设置方法
 * @param  {String} oldColor 为16进制色值的字符串（例：'#000000'）
 * @return {String} 返回反色的色值（例：'#ffffff'）
 */
this.colorReverse = function(oldColor) {
  // 如果是3位数的色值，补全成6位，
  const threeReg = /^#[0-9A-Fa-f]{3}$/;
  if (threeReg.test(oldColor)) {
    const testReg = /^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])/;
    oldColor = oldColor.replace(testReg, `#$1$1$2$2$3$3`);
  }
  oldColor = '0x' + oldColor.replace(/#/g, '');
  let str = '000000' + (0xFFFFFF - oldColor).toString(16);
  return '#'+ str.substring(str.length - 6, str.length);
}
/**
 * 255颜色值转16进制颜色值
 * @param n 255颜色值
 * @returns hex 16进制颜色值
 */
this.toHex = (n) => `${n > 15 ? '' : 0}${n.toString(16)}`;

/**
 * 颜色对象转化为16进制颜色字符串
 * @param colorObj 颜色对象
 */
this.toHexString = (colorObj) => {
  const { r, g, b, a = 1 } = colorObj;
  return `#${this.toHex(r)}${this.toHex(g)}${this.toHex(b)}${a === 1 ? '' : this.toHex(Math.floor(a * 255))}`;
};

/**
 * 颜色对象转化为rgb颜色字符串
 * @param colorObj 颜色对象
 */
this.toRgbString = (colorObj) => {
  const { r, g, b } = colorObj;
  return `rgb(${r},${g},${b})`;
};

/**
 * 颜色对象转化为rgba颜色字符串
 * @param colorObj 颜色对象
 */
this.toRgbaString = (colorObj, n = 10000) => {
  const { r, g, b, a = 1 } = colorObj;
  return `rgba(${r},${g},${b},${Math.floor(a * n ) / n})`;
};

/**
 * 16进制颜色字符串解析为颜色对象
 * @param color 颜色字符串
 * @returns IColorObj
 */
this.parseHexColor = (color) => {
  let hex = color.slice(1);
  let a = 1;
  if (hex.length === 3) {
    hex = `${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`;
  }
  if (hex.length === 8) {
    a = parseInt(hex.slice(6), 16) / 255;
    hex = hex.slice(0, 6);
  }
  const bigint = parseInt(hex, 16);
  return {
      r: (bigint >> 16) & 255,
      g: (bigint >> 8) & 255,
      b: bigint & 255,
      a,
  }
};

/**
 * rgba颜色字符串解析为颜色对象
 * @param color 颜色字符串
 * @returns IColorObj
 */
this.parseRgbaColor = (color) => {
  const arr = color.match(/(\d(\.\d+)?)+/g) || [];
  const res = arr.map((s) => parseInt(s, 10));
  return {
    r: res[0],
    g: res[1],
    b: res[2],
    a: parseFloat(arr[3]),
  }
};

/**
 * 颜色字符串解析为颜色对象
 * @param color 颜色字符串
 * @returns IColorObj
 */
this.parseColorString = (color) => {
  if (color.startsWith('#')) {
    return this.parseHexColor(color);
  } else if (color.startsWith('rgb')) {
    return this.parseRgbaColor(color);
  } else if (color === 'transparent') {
    return this.parseHexColor('#00000000');
  }
  throw new Error(`color string error: ${color}`);
};

/**
 * 颜色字符串解析为各种颜色表达方式
 * @param color 颜色字符串
 * @returns IColorObj
 */
this.getColorInfo = (color) => {
  const colorObj = this.parseColorString(color);
  const hex = this.toHexString(colorObj);
  const rgba = this.toRgbaString(colorObj);
  const rgb = this.toRgbString(colorObj);
  return {
    hex,
    rgba,
    rgb,
    rgbaObj: colorObj,
  };
};

/**
 * 16进制颜色字符串转化为rgba颜色字符串
 * @param hex 16进制颜色字符串
 * @returns rgba颜色字符串
 */
this.hexToRgba = (hex) => {
  const colorObj = this.parseColorString(hex);
  return this.toRgbaString(colorObj);
};

/**
 * rgba颜色字符串转化为16进制颜色字符串
 * @param rgba rgba颜色字符串
 * @returns 16进制颜色字符串
 */
this.rgbaToHex = (rgba) => {
  const colorObj = this.parseColorString(rgba);
  return this.toHexString(colorObj);
}

/** ------ 图片上传模块 开始 ------ */
this.doInput = () => {
  const inputObj = document.createElement('input');
  inputObj.addEventListener('change', this.readFile, false);
  inputObj.type = 'file';
  inputObj.accept = 'image/*';
  inputObj.click();
}
this.readFile = (arg) => {
  const file = arg.target.files[0]; // 获取input输入的图片
  if(!/image\/\w+/.test(file.type)){
      alert("请确保文件为图像类型");
      return false;
  } // 判断是否图片
  const reader = new FileReader();
  reader.readAsDataURL(file); // 转化成base64数据类型
  reader.onload = (e) => {
    this.drawToCanvas(e);
  }
}
this.drawToCanvas = (e) => {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  const imgObj = new Image()
  upload_img.src = imgObj.src = e.target.result
  imgObj.onload = () => {
    canvas.width = imgObj.width;
    canvas.height = imgObj.height;
    ctx.drawImage(imgObj, 0, 0)
    upload_r.value = this.getImageMainColor(canvas);
    upload_r_display.style.backgroundColor = upload_r.value;
  }
}